package com.situ.student.servlet;

import com.alibaba.fastjson2.JSON;
import com.situ.student.model.Student;
import com.situ.student.model.search.StudentSearchBean;
import com.situ.student.service.StudentService;
import com.situ.student.service.impl.StudentServiceImpl;
import com.situ.student.util.BeanFactory;
import com.situ.student.util.Pagination;
import com.situ.student.util.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@WebServlet("/admin/student/*")
public class StudentServlet extends HttpServlet {
    private StudentService studentService = BeanFactory.getBean(StudentServiceImpl.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getPathInfo();
        if ("/list".equals(action)) {
            //List<Student> students = studentService.findAll();
            //放到请求域中
            //req.setAttribute("students", students);

            /*String page = req.getParameter("page");
            String limit = req.getParameter("limit");
            System.out.println(page + ":" + limit);*/


            req.getRequestDispatcher("/WEB-INF/jsp/student/list.jsp").forward(req, resp);
        } else if ("/add".equals(action)) {
            req.getRequestDispatcher("/WEB-INF/jsp/student/add.jsp").forward(req, resp);
        } else if ("/edit".equals(action)) {
            String id = req.getParameter("id");
            req.setAttribute("id", id);
            req.getRequestDispatcher("/WEB-INF/jsp/student/edit.jsp").forward(req, resp);
        } else if ("/id".equals(action)) {//查询学生信息
            String id = req.getParameter("id");
            Student stu = studentService.findById(Integer.parseInt(id));
            ServletUtils.renderJson(resp, Map.of("student", stu));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getPathInfo();
        if ("/list".equals(action)) {//查询列表
            list(req, resp);
        } else if ("/delete".equals(action)) {//删除
            deleteByIds(req, resp);
        } else if ("/add".equals(action)) {//保存
            save(req, resp);
        } else if ("/edit".equals(action)) {
            edit(req, resp);
        }
    }

    //查询操作
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");//页码
        String limit = req.getParameter("limit");//页面大小
        //前端提交的查询条件
        String stuId = req.getParameter("stuId");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birthStart = req.getParameter("birthStart");
        String birthEnd = req.getParameter("birthEnd");
        String phone = req.getParameter("phone");

        //查询条件封装
        StudentSearchBean condition = new StudentSearchBean();
        if (StringUtils.hasText(stuId)) {
            condition.setStuId(stuId);
        }
        if (StringUtils.hasText(name)) {
            condition.setName(name);
        }
        if (StringUtils.hasText(sex)) {
            condition.setSex(sex);
        }
        if (StringUtils.hasText(phone)) {
            condition.setPhone(phone);
        }
        if (StringUtils.hasText(birthStart)) {
            LocalDate bs = LocalDate.parse(birthStart, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            condition.setBirthdayStart(bs);
        }
        if (StringUtils.hasText(birthEnd)) {
            LocalDate be = LocalDate.parse(birthEnd, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            condition.setBirthdayEnd(be);
        }


        int iPage = 1;
        if (StringUtils.hasText(page)) {
            try {
                iPage = Integer.parseInt(page);
            } catch (NumberFormatException e) {
                //iPage = 1;
            }
        }

        int iLimit = 20;
        if (StringUtils.hasText(limit)) {
            try {
                iLimit = Integer.parseInt(limit);
            } catch (NumberFormatException e) {
                //iLimit = 20;
            }
        }

        Pagination pagination = new Pagination(iPage, iLimit);
        List<Student> students = studentService.findAll(pagination, condition);
        Map<String, Object> map = Map.of("students", students, "pi", pagination);

        //设置响应内容格式为json
        resp.setContentType("application/json;charset=UTF-8");
        //将java对象序列化成json字符串
        String json = JSON.toJSONString(map);
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
    }

    //批量删除
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] strIds = req.getParameterValues("ids");

        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < strIds.length; i++) {
            ids.add(Integer.parseInt(strIds[i]));
        }

        int rows = studentService.deleteByIds(ids);
        Map<String, Object> map = Map.of("rows", rows);

        ServletUtils.renderJson(resp, map);
    }

    //保存学生
    private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuId = req.getParameter("stuId");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String pinyin = req.getParameter("pinyin");
        String phone = req.getParameter("phone");
        String wechat = req.getParameter("wechat");

        Student student = new Student();

        if (!StringUtils.hasText(stuId)) {
            ServletUtils.renderJson(resp, Map.of("error", "学号不可为空"));
            return;
        }

        student.setStuId(stuId);
        student.setName(name);
        if (!sex.equals("男") && !sex.equals("女")) {
            ServletUtils.renderJson(resp, Map.of("error", "性别数据不合法"));
            return;
        }
        student.setSex(sex);

        try {
            LocalDate ld = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            student.setBirthday(ld);
        } catch (Exception e) {
            ServletUtils.renderJson(resp, Map.of("error", "出生日期格式不正确"));
            return;
        }

        if (!phone.matches("^\\d{11}$")) {
            ServletUtils.renderJson(resp, Map.of("error", "手机号不正确"));
            return;
        }

        student.setPhone(phone);
        student.setPinyin(pinyin);
        student.setWechat(wechat);

        //调用业务类
        boolean success = studentService.save(student);

        ServletUtils.renderJson(resp, Map.of("success", success));
    }

    //修改
    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String stuId = req.getParameter("stuId");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String pinyin = req.getParameter("pinyin");
        String phone = req.getParameter("phone");
        String wechat = req.getParameter("wechat");

        Student student = new Student();
        student.setId(Integer.parseInt(id));

        if (!StringUtils.hasText(stuId)) {
            ServletUtils.renderJson(resp, Map.of("error", "学号不可为空"));
            return;
        }

        student.setStuId(stuId);
        student.setName(name);
        if (!sex.equals("男") && !sex.equals("女")) {
            ServletUtils.renderJson(resp, Map.of("error", "性别数据不合法"));
            return;
        }
        student.setSex(sex);

        try {
            LocalDate ld = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            student.setBirthday(ld);
        } catch (Exception e) {
            ServletUtils.renderJson(resp, Map.of("error", "出生日期格式不正确"));
            return;
        }

        if (!phone.matches("^\\d{11}$")) {
            ServletUtils.renderJson(resp, Map.of("error", "手机号不正确"));
            return;
        }

        student.setPhone(phone);
        student.setPinyin(pinyin);
        student.setWechat(wechat);

        //调用业务类
        boolean success = studentService.update(student);

        ServletUtils.renderJson(resp, Map.of("success", success));
    }
}
